from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import datetime, timedelta
from django.contrib.auth import get_user_model

User = get_user_model()

class Calendar(models.Model):
    """日历模型"""
    date = models.DateField(unique=True)
    year = models.IntegerField()
    month = models.IntegerField()

    class Meta:
        ordering = ['-date']
        verbose_name = '日历'
        verbose_name_plural = '日历'

    def __str__(self):
        return f"{self.year}年{self.month}月"

    def get_events_count(self):
        """获取该日历下的日程数量"""
        return self.events.count()

    def get_completed_count(self):
        """获取已完成的日程数量"""
        return self.events.filter(status='completed').count()


class ScheduleManager(models.Manager):
    """日程管理器"""

    def by_user(self, user):
        """获取用户的日程"""
        return self.filter(user=user)

    def today(self, user):
        """获取今日日程"""
        today = timezone.now().date()
        return self.filter(user=user, date=today)

    def upcoming(self, user, days=7):
        """获取未来日程"""
        today = timezone.now().date()
        end_date = today + timedelta(days=days)
        return self.filter(
            user=user,
            date__range=[today, end_date]
        )

    def by_status(self, user, status):
        """按状态查询"""
        return self.filter(user=user, status=status)

    def by_period(self, user, period):
        """按时间段查询"""
        return self.filter(user=user, period=period)


class Event(models.Model):
    """日程事件模型"""
    id = models.BigAutoField(primary_key=True)

    # 用户关联
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='events',
        verbose_name='用户',
        db_constraint=True,
        db_index=True
    )

    # 用户ID关联
    creator_id = models.BigIntegerField(
        verbose_name='创建者ID',
        help_text='关联创建者的ID',
        db_index=True,
        null=True  # 临时允许为空
    )

    # 关联用户
    related_users = models.ManyToManyField(
        User,
        related_name='related_events',
        blank=True,
        verbose_name="相关用户"
    )

    # 基础信息
    title = models.CharField(max_length=200, verbose_name="标题")
    description = models.TextField(blank=True, verbose_name="描述")
    date = models.DateField(verbose_name="日期")
    start_time = models.TimeField(verbose_name="开始时间")
    end_time = models.TimeField(verbose_name="结束时间")

    # 时间段和状态
    period = models.CharField(
        max_length=20,
        choices=[
            ('morning', '上午'),
            ('afternoon', '下午')
        ],
        verbose_name="时间段"
    )

    status = models.CharField(
        max_length=20,
        choices=[
            ('pending', '未完成'),
            ('completed', '已完成'),
            ('cancelled', '已取消')
        ],
        default='pending',
        verbose_name="状态"
    )

    # 重要程度
    importance = models.CharField(
        max_length=10,
        choices=[
            ('high', '高'),
            ('medium', '中'),
            ('low', '低')
        ],
        default='medium',
        verbose_name="重要程度"
    )

    # 提醒设置
    reminder = models.BooleanField(default=False, verbose_name="是否提醒")
    reminder_time = models.DateTimeField(null=True, blank=True, verbose_name="提醒时间")

    # 位置信息
    location = models.CharField(max_length=200, blank=True, verbose_name="地点")

    # 重复设置
    is_recurring = models.BooleanField(default=False, verbose_name="是否重复")
    recurring_pattern = models.CharField(
        max_length=20,
        choices=[
            ('daily', '每天'),
            ('weekly', '每周'),
            ('monthly', '每月')
        ],
        null=True,
        blank=True,
        verbose_name="重复模式"
    )
    recurring_end_date = models.DateField(
        null=True,
        blank=True,
        verbose_name="重复结束日期"
    )

    # AI 增强功能
    ai_suggestions = models.JSONField(
        default=dict,
        verbose_name="AI建议",
        help_text="包含时间安排、参与者等建议"
    )

    # 关联信息
    calendar = models.ForeignKey(
        'Calendar',
        on_delete=models.CASCADE,
        related_name='events',
        verbose_name="所属日历"
    )

    # 关联笔记ID
    related_note_id = models.IntegerField(
        null=True, 
        blank=True,
        db_index=True,  # 添加索引提高查询性能
        verbose_name="关联笔记ID"
    )

    # 来源标记
    from_note = models.BooleanField(
        default=False,
        verbose_name="是否来自笔记生成"
    )

    # 元数据
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    objects = ScheduleManager()

    class Meta:
        db_table = 'event'
        verbose_name = '日程'
        verbose_name_plural = '日程'
        ordering = ['date', 'start_time']
        indexes = [
            models.Index(fields=['date', 'period']),
            models.Index(fields=['status']),
            models.Index(fields=['user']),
            models.Index(fields=['creator_id'], name='event_creator_id_idx')  # 自定义索引名
        ]

    def __str__(self):
        return f"{self.date} {self.title}"

    def save(self, *args, **kwargs):
        # 保存前自动设置 creator_id
        if self.user and not self.creator_id:
            self.creator_id = self.user.id

        # 验证结束时间不早于开始时间
        if self.end_time < self.start_time:
            raise ValueError("结束时间不能早于开始时间")

        # 根据开始时间自动设置时间段
        if self.start_time.hour < 12:
            self.period = 'morning'
        else:
            self.period = 'afternoon'

        # 自动创建或获取对应的日历
        calendar, _ = Calendar.objects.get_or_create(
            date=self.date,
            defaults={
                'year': self.date.year,
                'month': self.date.month
            }
        )
        self.calendar = calendar

        super().save(*args, **kwargs)

    def get_duration(self):
        """获取持续时间（分钟）"""
        start = datetime.combine(self.date, self.start_time)
        end = datetime.combine(self.date, self.end_time)
        return (end - start).seconds // 60

    def is_overdue(self):
        """检查是否已过期"""
        now = timezone.now()
        event_datetime = datetime.combine(self.date, self.end_time)
        return event_datetime < now and self.status == 'pending'

    def get_participant_list(self):
        """获取参与者列表"""
        return list(self.related_users.values('id', 'username'))

    def mark_as_completed(self):
        """标记为已完成"""
        self.status = 'completed'
        self.save()

    def mark_as_cancelled(self):
        """标记为已取消"""
        self.status = 'cancelled'
        self.save()

    def update_ai_suggestions(self, suggestions):
        """更新AI建议"""
        self.ai_suggestions = suggestions
        self.save()

    def add_participant(self, user):
        """添加参与者"""
        if user not in self.related_users.all():
            self.related_users.add(user)

    def remove_participant(self, user):
        """移除参与者"""
        self.related_users.remove(user)

    def create_recurring_events(self):
        """创建重复日程"""
        if not self.is_recurring or not self.recurring_pattern:
            return []

        events = []
        current_date = self.date
        end_date = self.recurring_end_date or (current_date + timedelta(days=365))

        while current_date <= end_date:
            if self.recurring_pattern == 'daily':
                current_date += timedelta(days=1)
            elif self.recurring_pattern == 'weekly':
                current_date += timedelta(days=7)
            elif self.recurring_pattern == 'monthly':
                # 处理月份变化
                year = current_date.year + ((current_date.month + 1) // 12)
                month = ((current_date.month + 1) % 12) or 12
                current_date = current_date.replace(year=year, month=month)

            if current_date <= end_date:
                event = Event.objects.create(
                    title=self.title,
                    description=self.description,
                    date=current_date,
                    start_time=self.start_time,
                    end_time=self.end_time,
                    importance=self.importance,
                    location=self.location,
                    user=self.user
                )
                events.append(event)

        return events


class EventChat(models.Model):
    """日程AI对话记录"""
    event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='chats')
    user_message = models.TextField(verbose_name="用户消息")
    ai_response = models.TextField(verbose_name="AI回复")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        db_table = 'event_chat'
        verbose_name = '日程对话记录'
        verbose_name_plural = '日程对话记录'

    def __str__(self):
        return f"{self.event.title} - {self.created_at}"
